package com.tk.ad.sdk.api;

import android.Manifest;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.tk.ad.sdk.comment.AppSharePreUtils;
import com.tk.ad.sdk.http.HttpConfig;
import com.tk.ad.sdk.http.OKHttpUtils;
import com.tk.ad.sdk.utils.AppLog;
import com.tk.ad.sdk.utils.DeviceUuidFactory;
import com.tk.ad.sdk.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Response;

/**
 * Created by hsy on 2017/4/24.
 */

public class ADApi {


    public static ADApi mInstance;

    private Context mContext;

    private String mAppKey;

    public static ADApi getInstance(Context context) {

        if (mInstance == null) {
            mInstance = new ADApi(context);
        }

        return mInstance;
    }

    public void init() {

        if (TextUtils.isEmpty(getAppKey())) {
            AppLog.getInstance().e("TK_APPKEY为null，请到AndroidManifest.xml配置appkey");
        }
        SharedPreferencesUtils.init(mContext);
    }

    public String getAppKey() {

        if (TextUtils.isEmpty(mAppKey)) {
            ApplicationInfo appInfo = null;
            try {
                appInfo = mContext.getPackageManager()
                        .getApplicationInfo(mContext.getPackageName(),
                                PackageManager.GET_META_DATA);

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            Bundle metaData = appInfo.metaData;
            if(metaData != null){
                mAppKey = appInfo.metaData.getString("TK_APPKEY");
            }
        }

        return mAppKey;
    }

    public void setAppKey(String appKey) {
        mAppKey = appKey;
    }

    public ADApi(Context context) {
        mContext = context;
    }

    public void sendAdTrack() {

        if(!AppSharePreUtils.isFirstSendTrack()){
            return;
        }

        String appkey = getAppKey();

        if (TextUtils.isEmpty(appkey)) {
            return;
        }
        String device_name = Build.MODEL;
        String imei = DeviceUuidFactory.getUniquePsuedoID();
        String mac = getMacAddress();
        String os = "android";
        String os_version = android.os.Build.VERSION.RELEASE;

//        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//        PackageManager pm = mContext.getPackageManager();


//        if (pm.checkPermission(Manifest.permission.READ_PHONE_STATE,
//                mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
//            imei = tm.getDeviceId();
//        } else {
////            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
////                    1);
//        }

//        String androidId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

//        厂商定制系统的Bug：不同的设备可能会产生相同的ANDROID_ID：9774d56d682e549c。
//        厂商定制系统的Bug：有些设备返回的值为null。
//        设备差异：对于CDMA设备，ANDROID_ID和TelephonyManager.getDeviceId() 返回相同的值。

//        String utdid1 = com.ta.utdid2.device.UTDevice.getUtdid(mContext);
//        String utdid2 = UTDevice.getUtdid(mContext);
//        AppLog.getInstance().v("androidId:"+androidId);
//        AppLog.getInstance().v("utdid1:"+utdid1);
//        AppLog.getInstance().v("utdid2:"+utdid2);

//        WQwiq/26df0DAJm9a1W46YOb   WQwi+Xg1JasDACGc3K7nn96w
//        feb13292ad5b66df

//        if (pm.checkPermission(Manifest.permission.ACCESS_WIFI_STATE,
//                mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
//
//            WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
//            WifiInfo info = wifi.getConnectionInfo();
//            mac = info.getMacAddress();
//        }

        HttpUrl.Builder urlBuilder = HttpUrl.parse(HttpConfig.APP_URL).newBuilder();
        urlBuilder.addQueryParameter("appkey", appkey);
        urlBuilder.addQueryParameter("device_name", device_name);
        urlBuilder.addQueryParameter("imei", imei);
        urlBuilder.addQueryParameter("mac", mac);
        urlBuilder.addQueryParameter("os", os);
        urlBuilder.addQueryParameter("os_version", os_version);

        AppLog.getInstance().v("ad_request:" + urlBuilder.build().toString());

        OKHttpUtils.getInstance().get(urlBuilder.build(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AppLog.getInstance().v("ad_result:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                AppSharePreUtils.setFirstSendTrack(false);
                AppLog.getInstance().v("ad_result:" + response.body().string());
//                {"msg":"更新成功","status":1}
//                {"msg":"更新失敗","status":0}
//                {"msg":"存在IP，APPkey，IMEI一樣的。","status":0}
//                {"name":"Internal Server Error","message":"服务器内部错误。","code":0,"status":500}
            }
        });
    }


    private String getMacAddress() {
        String macAddress = null;
        try {
            String wifiInterfaceName = "wlan0";
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iF = interfaces.nextElement();
                if (iF.getName().equalsIgnoreCase(wifiInterfaceName)) {
                    byte[] addr = iF.getHardwareAddress();
                    if (addr == null || addr.length == 0) {
                        return null;
                    }

                    StringBuilder buf = new StringBuilder();
                    for (byte b : addr) {
                        buf.append(String.format("%02X:", b));
                    }
                    if (buf.length() > 0) {
                        buf.deleteCharAt(buf.length() - 1);
                    }
                    macAddress = buf.toString();
                    break;
                }
            }
        } catch (SocketException se) {
            macAddress = null;
        }

        if (TextUtils.isEmpty(macAddress)) {

            PackageManager pm = mContext.getPackageManager();


            if (pm.checkPermission(Manifest.permission.ACCESS_WIFI_STATE,
                    mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) {

                WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifi.getConnectionInfo();
                macAddress = info.getMacAddress();
            }
        }

        return macAddress;
    }
}
